import { useContext, useEffect, useMemo, useState } from 'react';
import { isUploadComplete } from '../../utils/tool';
import { InBizUploadCtx } from '../../context';

const Progress = (props: any) => {
  const { id, className, style } = props;
  const [bytesUploaded, setBytesUploaded] = useState(0);
  const [totalSize, setTotalSize] = useState(0);
  const [hidden, setHidden] = useState(true);
  const { uploader, statusEnum } = useContext(InBizUploadCtx);
  const isTotalProgress = id == null;
  const progress_className = isTotalProgress
    ? 'react-fine-uploader-total-progress-bar'
    : 'react-fine-uploader-file-progress-bar';
  const customContainerClassName = className ? className + '-container' : '';
  const percentWidth = useMemo(() => {
    return (bytesUploaded / totalSize) * 100 || 0;
  }, [bytesUploaded, totalSize]);

  const totalProgressEventHandler = (bytesUploaded: number, totalSize: number) => {
    setBytesUploaded(bytesUploaded);
    setTotalSize(totalSize);
  };
  const progressEventHandler = (
    fileId: number,
    name: string,
    bytesUploaded: number,
    totalSize: number,
  ) => {
    if (fileId === id) {
      setBytesUploaded(bytesUploaded);
      setTotalSize(totalSize);
      setHidden(false);
    }
  };
  const statusEventHandler = (fileId: number, oldStatus: string, newStatus: string) => {
    if (isTotalProgress) {
      setHidden((state) => {
        if (
          !state &&
          isUploadComplete(newStatus, statusEnum) &&
          !uploader.methods.getInProgress()
        ) {
          return true;
        } else if (state && uploader.methods.getInProgress()) {
          return false;
        }
        return state;
      });
    } else if (fileId === id) {
      setHidden((state) => {
        if (state && (newStatus === statusEnum.UPLOADING || newStatus === statusEnum.QUEUED)) {
          return false;
        } else if (!state && isUploadComplete(newStatus, statusEnum)) {
          return true;
        }
        return state;
      });
    }
  };

  useEffect(() => {
    if (isTotalProgress) {
      uploader.on('totalProgress', totalProgressEventHandler);
    } else {
      uploader.on('progress', progressEventHandler);
    }
    uploader.on('statusChange', statusEventHandler);
    return () => {
      if (isTotalProgress) {
        uploader.off('totalProgress', totalProgressEventHandler);
      } else {
        uploader.off('progress', progressEventHandler);
      }
      uploader.off('statusChange', statusEventHandler);
    };
  }, []);

  return (
    <div className={`${progress_className}-container ${customContainerClassName}`} hidden={hidden} style={style}>
      <div
        aria-valuemax={100}
        aria-valuemin={0}
        aria-valuenow={percentWidth}
        className={`${progress_className} ${className || ''}`}
        role="progressbar"
        style={{ width: percentWidth + '%' }}
      ></div>
    </div>
  );
};

export default Progress;
